<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="springboot入门"><meta name="keywords" content="springboot"><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>springboot入门 | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#springboot%E5%85%A5%E9%97%A8"><span class="toc-number">1.</span> <span class="toc-text">springboot入门</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%A1%B9%E7%9B%AE%E4%BE%9D%E8%B5%96%E8%A7%A3%E6%9E%90"><span class="toc-number">1.1.</span> <span class="toc-text">项目依赖解析</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E5%BD%95%E7%BB%93%E6%9E%84"><span class="toc-number">1.2.</span> <span class="toc-text">目录结构</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#src-main-resources%E7%9B%AE%E5%BD%95%E6%98%AFSpring-Boot%E7%9A%84%E9%85%8D%E7%BD%AE%E7%9B%AE%E5%BD%95"><span class="toc-number">1.2.0.1.</span> <span class="toc-text">src&#x2F;main&#x2F;resources目录是Spring Boot的配置目录</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4%E8%A1%8C%E6%89%A7%E8%A1%8C"><span class="toc-number">1.2.0.2.</span> <span class="toc-text">命令行执行</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%A4%9A%E7%8E%AF%E5%A2%83%E9%85%8D%E7%BD%AE"><span class="toc-number">1.2.0.3.</span> <span class="toc-text">多环境配置</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E7%BB%91%E5%AE%9A"><span class="toc-number">1.2.1.</span> <span class="toc-text">配置文件绑定</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.2.1.1.</span> <span class="toc-text">简单类型</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#List%E7%B1%BB%E5%9E%8B"><span class="toc-number">1.2.1.2.</span> <span class="toc-text">List类型</span></a></li></ol></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#api%E5%BC%80%E5%8F%91"><span class="toc-number">1.3.</span> <span class="toc-text">api开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#swagger%E5%88%9B%E5%BB%BAapi%E6%96%87%E6%A1%A3"><span class="toc-number">1.4.</span> <span class="toc-text">swagger创建api文档</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E6%96%87%E6%A1%A3%E5%86%85%E5%AE%B9"><span class="toc-number">1.4.1.</span> <span class="toc-text">添加文档内容</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0%E6%A0%A1%E9%AA%8C-jsr-303"><span class="toc-number">1.5.</span> <span class="toc-text">请求参数校验 jsr-303</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%94%AF%E6%8C%81%E6%95%B0%E6%8D%AE%E5%BA%93"><span class="toc-number">1.6.</span> <span class="toc-text">支持数据库</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#mybatis"><span class="toc-number">1.6.1.</span> <span class="toc-text">mybatis</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA"><span class="toc-number">1.6.1.1.</span> <span class="toc-text">创建</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8Map"><span class="toc-number">1.6.1.2.</span> <span class="toc-text">使用Map</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8%E5%AF%B9%E8%B1%A1"><span class="toc-number">1.6.1.3.</span> <span class="toc-text">使用对象</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5"><span class="toc-number">1.6.1.4.</span> <span class="toc-text">增删改查</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E8%BF%94%E5%9B%9E%E7%BB%93%E6%9E%9C%E7%BB%91%E5%AE%9A"><span class="toc-number">1.6.1.5.</span> <span class="toc-text">返回结果绑定</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BA%8B%E5%8A%A1"><span class="toc-number">1.6.2.</span> <span class="toc-text">事务</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%BC%93%E5%AD%98"><span class="toc-number">1.7.</span> <span class="toc-text">缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Cache%E9%85%8D%E7%BD%AE%E6%B3%A8%E8%A7%A3%E8%AF%A6%E8%A7%A3"><span class="toc-number">1.7.1.</span> <span class="toc-text">Cache配置注解详解</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#async%E5%AE%9E%E7%8E%B0%E5%BC%82%E6%AD%A5%E4%BB%BB%E5%8A%A1"><span class="toc-number">1.8.</span> <span class="toc-text">async实现异步任务</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BC%82%E6%AD%A5%E5%9B%9E%E8%B0%83"><span class="toc-number">1.8.1.</span> <span class="toc-text">异步回调</span></a></li></ol></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">springboot入门</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-11-19</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">5.4k</span><span class="post-meta__separator">|</span><span>阅读时长: 22 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h2 id="springboot入门"><a href="#springboot入门" class="headerlink" title="springboot入门"></a>springboot入门</h2><p>不求能写，但求能看</p>
<p><a target="_blank" rel="noopener" href="https://gitee.com/didispace/SpringBoot-Learning/tree/master/2.x#http://blog.didispace.com/spring-boot-learning-21-1-1/">学习地址</a></p>
<h3 id="项目依赖解析"><a href="#项目依赖解析" class="headerlink" title="项目依赖解析"></a>项目依赖解析</h3><p>打开<code>pom.xml</code>，一起来看看Spring Boot项目的依赖：</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">project</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0&quot;</span> <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">	<span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">modelVersion</span>&gt;</span>4.0.0<span class="tag">&lt;/<span class="name">modelVersion</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">parent</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-parent<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.1.3.RELEASE<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">relativePath</span>/&gt;</span> <span class="comment">&lt;!-- lookup parent from repository --&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">parent</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.didispace<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>chapter1-1<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.0.1-SNAPSHOT<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">name</span>&gt;</span>chapter1-1<span class="tag">&lt;/<span class="name">name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">description</span>&gt;</span>Demo project for Spring Boot<span class="tag">&lt;/<span class="name">description</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">java.version</span>&gt;</span>1.8<span class="tag">&lt;/<span class="name">java.version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-test<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">scope</span>&gt;</span>test<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">build</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">plugins</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">plugin</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-maven-plugin<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">plugin</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">plugins</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">build</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">project</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>主要有四个部分：</p>
<ul>
<li>项目元数据：创建时候输入的Project Metadata部分，也就是Maven项目的基本元素，包括：groupId、artifactId、version、name、description等</li>
<li>parent：继承<code>spring-boot-starter-parent</code>的依赖管理，控制版本与打包等内容</li>
<li>dependencies：项目具体依赖，这里包含了<code>spring-boot-starter-web</code>用于实现HTTP接口（该依赖中包含了Spring MVC）；<code>spring-boot-starter-test</code>用于编写单元测试的依赖包。更多功能模块的使用我们将在后面的教程中逐步展开。</li>
<li>build：构建配置部分。默认使用了<code>spring-boot-maven-plugin</code>，配合<code>spring-boot-starter-parent</code>就可以把Spring Boot应用打包成JAR来直接运行。</li>
</ul>
<h3 id="目录结构"><a href="#目录结构" class="headerlink" title="目录结构"></a>目录结构</h3><p>就是里面的而一些文件是干嘛的。</p>
<p>以下结构是比较推荐的package组织方式：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">com</span><br><span class="line">  +- example</span><br><span class="line">    +- myproject</span><br><span class="line">      +- Application.java</span><br><span class="line">      |</span><br><span class="line">      +- domain</span><br><span class="line">      |  +- Customer.java</span><br><span class="line">      |  +- CustomerRepository.java</span><br><span class="line">      |</span><br><span class="line">      +- service</span><br><span class="line">      |  +- CustomerService.java</span><br><span class="line">      |</span><br><span class="line">      +- web</span><br><span class="line">      |  +- CustomerController.java</span><br><span class="line">      |</span><br></pre></td></tr></table></figure>

<ul>
<li><code>root package</code>：<code>com.example.myproject</code>，所有的类和其他package都在root package之下。</li>
<li>应用主类：<code>Application.java</code>，该类直接位于<code>root package</code>下。通常我们会在应用主类中做一些框架配置扫描等配置，我们放在root package下可以帮助程序减少手工配置来加载到我们希望被Spring加载的内容</li>
<li><code>com.example.myproject.domain</code>包：用于定义实体映射关系与数据访问相关的接口和实现</li>
<li><code>com.example.myproject.service</code>包：用于编写业务逻辑相关的接口与实现</li>
<li><code>com.example.myproject.web</code>：用于编写Web层相关的实现，比如：Spring MVC的Controller等</li>
</ul>
<p>上面的结构中，<code>root package</code>与应用主类的位置是整个结构的关键。由于应用主类在<code>root package</code>中，所以按照上面的规则定义的所有其他类都处于<code>root package</code>下的其他子包之后。默认情况下，Spring Boot的应用主类会自动扫描<code>root package</code>以及所有子包下的所有类来进行初始化</p>
<h5 id="src-main-resources目录是Spring-Boot的配置目录"><a href="#src-main-resources目录是Spring-Boot的配置目录" class="headerlink" title="src/main/resources目录是Spring Boot的配置目录"></a><code>src/main/resources</code>目录是Spring Boot的配置目录</h5><p><strong>application.properties：</strong>配置文件（使用yaml格式），可在里面配置端口之类的，还可自定义属性，并使用@value(xxx)注解在类中使用。但好像还有一个application.yml文件，似乎也是同样的功能</p>
<h5 id="命令行执行"><a href="#命令行执行" class="headerlink" title="命令行执行"></a>命令行执行</h5><p><code>java -jar xxx.jar --server.port=8888</code>，直接以命令行的方式，来设置server.port属性，另启动应用的端口设为8888。</p>
<p>等价于我们在<code>application.properties</code>中添加属性<code>server.port=8888</code></p>
<h5 id="多环境配置"><a href="#多环境配置" class="headerlink" title="多环境配置"></a>多环境配置</h5><p>在Spring Boot中多环境配置文件名需要满足<code>application-&#123;profile&#125;.properties</code>的格式，其中<code>&#123;profile&#125;</code>对应你的环境标识，比如：</p>
<ul>
<li><code>application-dev.properties</code>：开发环境</li>
<li><code>application-test.properties</code>：测试环境</li>
<li><code>application-prod.properties</code>：生产环境</li>
</ul>
<p>至于哪个具体的配置文件会被加载，需要在<code>application.properties</code>文件中通过<code>spring.profiles.active</code>属性来设置，其值对应配置文件中的<code>&#123;profile&#125;</code>值。如：<code>spring.profiles.active=test</code>就会加载<code>application-test.properties</code>配置文件内容。</p>
<h4 id="配置文件绑定"><a href="#配置文件绑定" class="headerlink" title="配置文件绑定"></a>配置文件绑定</h4><h5 id="简单类型"><a href="#简单类型" class="headerlink" title="简单类型"></a>简单类型</h5><p>在Spring Boot 2.0中对配置属性加载的时候会除了像1.x版本时候那样<strong>移除特殊字符</strong>外，还会将配置均以<strong>全小写</strong>的方式进行匹配和加载。所以，下面的4种配置方式都是等价的：</p>
<ul>
<li>properties格式：</li>
</ul>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">spring.jpa.databaseplatform=mysql</span><br><span class="line">spring.jpa.database-platform=mysql</span><br><span class="line">spring.jpa.databasePlatform=mysql</span><br><span class="line">spring.JPA.database_platform=mysql</span><br></pre></td></tr></table></figure>

<ul>
<li>yaml格式：</li>
</ul>
<figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">jpa:</span></span><br><span class="line">    <span class="attr">databaseplatform:</span> <span class="string">mysql</span></span><br><span class="line">    <span class="attr">database-platform:</span> <span class="string">mysql</span></span><br><span class="line">    <span class="attr">databasePlatform:</span> <span class="string">mysql</span></span><br><span class="line">    <span class="attr">database_platform:</span> <span class="string">mysql</span></span><br></pre></td></tr></table></figure>

<p><strong>Tips：推荐使用全小写配合<code>-</code>分隔符的方式来配置，比如：<code>spring.jpa.database-platform=mysql</code></strong></p>
<h5 id="List类型"><a href="#List类型" class="headerlink" title="List类型"></a>List类型</h5><p>在properties文件中使用<code>[]</code>来定位列表类型，比如：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">spring.my-example.url[0]=http://example.com</span><br><span class="line">spring.my-example.url[1]=http://spring.io</span><br></pre></td></tr></table></figure>

<p>也支持使用<strong>逗号</strong>分割的配置方式，上面与下面的配置是等价的：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">spring.my-example.url=http://example.com,http://spring.io</span><br></pre></td></tr></table></figure>

<p>而在yaml文件中使用可以使用如下配置：</p>
<figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">my-example:</span></span><br><span class="line">    <span class="attr">url:</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">http://example.com</span></span><br><span class="line">      <span class="bullet">-</span> <span class="string">http://spring.io</span></span><br></pre></td></tr></table></figure>

<p>也支持<strong>逗号</strong>分割的方式：</p>
<figure class="highlight yaml"><table><tr><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">my-example:</span></span><br><span class="line">    <span class="attr">url:</span> <span class="string">http://example.com,</span> <span class="string">http://spring.io</span></span><br></pre></td></tr></table></figure>



<h3 id="api开发"><a href="#api开发" class="headerlink" title="api开发"></a>api开发</h3><ul>
<li><code>@Controller</code>：修饰class，用来创建处理http请求的对象</li>
<li><code>@RestController</code>：Spring4之后加入的注解，原来在<code>@Controller</code>中返回json需要<code>@ResponseBody</code>来配合，如果直接用<code>@RestController</code>替代<code>@Controller</code>就不需要再配置<code>@ResponseBody</code>，默认返回json格式</li>
<li><code>@RequestMapping</code>：配置url映射。现在更多的也会直接用以Http Method直接关联的映射注解来定义，比如：<code>GetMapping</code>、<code>PostMapping</code>、<code>DeleteMapping</code>、<code>PutMapping</code>等。<a target="_blank" rel="noopener" href="https://blog.didispace.com/spring-boot-learning-21-2-1/">具体看这里</a></li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意：相比<a target="_blank" rel="noopener" href="http://blog.didispace.com/springbootrestfulapi/">1.x版本教程</a>中自定义set和get函数的方式，这里使用<code>@Data</code>注解可以实现在编译器自动添加set和get函数的效果。该注解是lombok提供的，只需要在pom中引入加入下面的依赖就可以支持：</p>
<figure class="highlight xml"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.projectlombok<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>lombok<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h3 id="swagger创建api文档"><a href="#swagger创建api文档" class="headerlink" title="swagger创建api文档"></a>swagger创建api文档</h3><p>默认情况下，Swagger是以<code>Controller</code>为单位，对接口进行分组管理的。这个分组的元素在Swagger中称为<code>Tag</code>，但是这里的<code>Tag</code>与接口的关系并不是一对多的，它支持更丰富的多对多关系</p>
<p><strong>第一步</strong>：添加swagger-spring-boot-starter依赖</p>
<p>在<code>pom.xml</code>中加入依赖，具体如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;com.spring4all&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;swagger-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.9.0.RELEASE&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<p><strong>第二步</strong>：应用主类中添加<code>@EnableSwagger2Doc</code>注解，具体如下</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">@EnableSwagger2Doc</span><br><span class="line">@SpringBootApplication</span><br><span class="line">public class Chapter22Application &#123;</span><br><span class="line"></span><br><span class="line">    public static void main(String[] args) &#123;</span><br><span class="line">        SpringApplication.run(Chapter22Application.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>第三步</strong>：<code>application.properties</code>中配置文档相关内容，比如</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">swagger.title=spring-boot-starter-swagger</span><br><span class="line">swagger.description=Starter for swagger 2.x</span><br><span class="line">swagger.version=1.4.0.RELEASE</span><br><span class="line">swagger.license=Apache License, Version 2.0</span><br><span class="line">swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html</span><br><span class="line">swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger</span><br><span class="line">swagger.contact.name=didi</span><br><span class="line">swagger.contact.url=http://blog.didispace.com</span><br><span class="line">swagger.contact.email=dyc87112@qq.com</span><br><span class="line">swagger.base-package=com.didispace</span><br><span class="line">swagger.base-path=/**</span><br></pre></td></tr></table></figure>

<p>各参数配置含义如下：</p>
<ul>
<li><code>swagger.title</code>：标题</li>
<li><code>swagger.description</code>：描述</li>
<li><code>swagger.version</code>：版本</li>
<li><code>swagger.license</code>：许可证</li>
<li><code>swagger.licenseUrl</code>：许可证URL</li>
<li><code>swagger.termsOfServiceUrl</code>：服务条款URL</li>
<li><code>swagger.contact.name</code>：维护人</li>
<li><code>swagger.contact.url</code>：维护人URL</li>
<li><code>swagger.contact.email</code>：维护人email</li>
<li><code>swagger.base-package</code>：swagger扫描的基础包，默认：全扫描</li>
<li><code>swagger.base-path</code>：需要处理的基础URL规则，默认：/**</li>
</ul>
<h4 id="添加文档内容"><a href="#添加文档内容" class="headerlink" title="添加文档内容"></a>添加文档内容</h4><p>在整合完Swagger之后，在<code>http://localhost:8080/swagger-ui.html</code>页面中可以看到，关于各个接口的描述还都是英文或遵循代码定义的名称产生的。这些内容对用户并不友好，所以我们需要自己增加一些说明来丰富文档内容。如下所示，我们通过<code>@Api</code>，<code>@ApiOperation</code>注解来给API增加说明、通过<code>@ApiImplicitParam</code>、<code>@ApiModel</code>、<code>@ApiModelProperty</code>注解来给参数增加说明。</p>
<p>比如下面的例子：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Api(tags = &quot;用户管理&quot;)</span></span><br><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="meta">@RequestMapping(value = &quot;/users&quot;)</span>     <span class="comment">// 通过这里配置使下面的映射都在/users下</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UserController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建线程安全的Map，模拟users信息的存储</span></span><br><span class="line">    <span class="keyword">static</span> Map&lt;Long, User&gt; users = Collections.synchronizedMap(<span class="keyword">new</span> HashMap&lt;&gt;());</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/&quot;)</span></span><br><span class="line">    <span class="meta">@ApiOperation(value = &quot;获取用户列表&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;User&gt; <span class="title">getUserList</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;User&gt; r = <span class="keyword">new</span> ArrayList&lt;&gt;(users.values());</span><br><span class="line">        <span class="keyword">return</span> r;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostMapping(&quot;/&quot;)</span></span><br><span class="line">    <span class="meta">@ApiOperation(value = &quot;创建用户&quot;, notes = &quot;根据User对象创建用户&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">postUser</span><span class="params">(<span class="meta">@RequestBody</span> User user)</span> </span>&#123;</span><br><span class="line">        users.put(user.getId(), user);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping(&quot;/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="meta">@ApiOperation(value = &quot;获取用户详细信息&quot;, notes = &quot;根据url的id来获取用户详细信息&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> User <span class="title">getUser</span><span class="params">(<span class="meta">@PathVariable</span> Long id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> users.get(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PutMapping(&quot;/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="meta">@ApiImplicitParam(paramType = &quot;path&quot;, dataType = &quot;Long&quot;, name = &quot;id&quot;, value = &quot;用户编号&quot;, required = true, example = &quot;1&quot;)</span></span><br><span class="line">    <span class="meta">@ApiOperation(value = &quot;更新用户详细信息&quot;, notes = &quot;根据url的id来指定更新对象，并根据传过来的user信息来更新用户详细信息&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">putUser</span><span class="params">(<span class="meta">@PathVariable</span> Long id, <span class="meta">@RequestBody</span> User user)</span> </span>&#123;</span><br><span class="line">        User u = users.get(id);</span><br><span class="line">        u.setName(user.getName());</span><br><span class="line">        u.setAge(user.getAge());</span><br><span class="line">        users.put(id, u);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@DeleteMapping(&quot;/&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="meta">@ApiOperation(value = &quot;删除用户&quot;, notes = &quot;根据url的id来指定删除对象&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">deleteUser</span><span class="params">(<span class="meta">@PathVariable</span> Long id)</span> </span>&#123;</span><br><span class="line">        users.remove(id);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@ApiModel(description=&quot;用户实体&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户编号&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户姓名&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户年龄&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><img src="http://img.didispace.com/FoxwzIgdkIIx6Z5_U8DZq5MqVQf_" alt="img"></p>
<h3 id="请求参数校验-jsr-303"><a href="#请求参数校验-jsr-303" class="headerlink" title="请求参数校验 jsr-303"></a>请求参数校验 jsr-303</h3><p><img src="http://img.didispace.com/Fugzgq1zvxjKur4qdm_N-xV5twMj" alt="img"></p>
<p><img src="http://img.didispace.com/FnNRRGx1eWbniJFHQz2m-pUIEWKa" alt="img"></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@ApiModel(description=&quot;用户实体&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户编号&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span></span><br><span class="line">    <span class="meta">@Size(min = 2, max = 5)</span></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户姓名&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span></span><br><span class="line">    <span class="meta">@Max(100)</span></span><br><span class="line">    <span class="meta">@Min(10)</span></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户年龄&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@NotNull</span></span><br><span class="line">    <span class="meta">@Email</span></span><br><span class="line">    <span class="meta">@ApiModelProperty(&quot;用户邮箱&quot;)</span></span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="支持数据库"><a href="#支持数据库" class="headerlink" title="支持数据库"></a>支持数据库</h3><h4 id="mybatis"><a href="#mybatis" class="headerlink" title="mybatis"></a>mybatis</h4><h5 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h5><p>在<code>pom.xml</code>中引入MyBatis的Starter以及MySQL Connector依赖，具体如下：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.mybatis.spring.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;mybatis-spring-boot-starter&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;2.1.1&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line"></span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;mysql&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<p>在<code>application.properties</code>中配置mysql的连接配置</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">spring.datasource.url=jdbc:mysql://localhost:3306/test</span><br><span class="line">spring.datasource.username=root</span><br><span class="line">spring.datasource.password=</span><br><span class="line">spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver</span><br></pre></td></tr></table></figure>

<p>创建User表的映射对象User：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="meta">@NoArgsConstructor</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> Long id;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="keyword">private</span> Integer age;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">(String name, Integer age)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">        <span class="keyword">this</span>.age = age;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建User表的操作接口：<strong>UserMapper</strong>。在接口中定义两个数据操作，一个插入，一个查询，用于后续单元测试验证。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Mapper</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select(&quot;SELECT * FROM USER WHERE NAME = #&#123;name&#125;&quot;)</span></span><br><span class="line">    <span class="function">User <span class="title">findByName</span><span class="params">(<span class="meta">@Param(&quot;name&quot;)</span> String name)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Insert(&quot;INSERT INTO USER(NAME, AGE) VALUES(#&#123;name&#125;, #&#123;age&#125;)&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">insert</span><span class="params">(<span class="meta">@Param(&quot;name&quot;)</span> String name, <span class="meta">@Param(&quot;age&quot;)</span> Integer age)</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建Spring Boot主类</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chapter35Application</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		SpringApplication.run(Chapter35Application.class, args);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>创建单元测试。具体测试逻辑如下：</p>
<ul>
<li>插入一条name=AAA，age=20的记录，然后根据name=AAA查询，并判断age是否为20</li>
<li>测试结束回滚数据，保证测试单元每次运行的数据环境独立</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@RunWith(SpringRunner.class)</span></span><br><span class="line"><span class="meta">@SpringBootTest</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chapter35ApplicationTests</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserMapper userMapper;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="meta">@Rollback</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        userMapper.insert(<span class="string">&quot;AAA&quot;</span>, <span class="number">20</span>);</span><br><span class="line">        User u = userMapper.findByName(<span class="string">&quot;AAA&quot;</span>);</span><br><span class="line">        Assert.assertEquals(<span class="number">20</span>, u.getAge().intValue());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>@Slf4j是用来输出日志的</p>
<h5 id="使用Map"><a href="#使用Map" class="headerlink" title="使用Map"></a>使用Map</h5><p>如下代码，通过<code>Map&lt;String, Object&gt;</code>对象来作为传递参数的容器：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">@Insert(&quot;INSERT INTO USER(NAME, AGE) VALUES(#&#123;name,jdbcType=VARCHAR&#125;, #&#123;age,jdbcType=INTEGER&#125;)&quot;)</span><br><span class="line">int insertByMap(Map&lt;String, Object&gt; map);</span><br></pre></td></tr></table></figure>

<p>对于Insert语句中需要的参数，我们只需要在map中填入同名的内容即可，具体如下面代码所示：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();</span><br><span class="line">map.put(&quot;name&quot;, &quot;CCC&quot;);</span><br><span class="line">map.put(&quot;age&quot;, 40);</span><br><span class="line">userMapper.insertByMap(map);</span><br></pre></td></tr></table></figure>

<h5 id="使用对象"><a href="#使用对象" class="headerlink" title="使用对象"></a>使用对象</h5><p>除了Map对象，我们也可直接使用普通的Java对象来作为查询条件的传参，比如我们可以直接使用User对象:</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">@Insert(&quot;INSERT INTO USER(NAME, AGE) VALUES(#&#123;name&#125;, #&#123;age&#125;)&quot;)</span><br><span class="line">int insertByUser(User user);</span><br></pre></td></tr></table></figure>

<p>这样语句中的<code>#&#123;name&#125;</code>、<code>#&#123;age&#125;</code>就分别对应了User对象中的<code>name</code>和<code>age</code>属性。</p>
<h5 id="增删改查"><a href="#增删改查" class="headerlink" title="增删改查"></a>增删改查</h5><p>MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置，在之前的示例中演示了<code>@Insert</code>，下面针对User表做一组最基本的增删改查作为示例：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserMapper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Select(&quot;SELECT * FROM user WHERE name = #&#123;name&#125;&quot;)</span></span><br><span class="line">    <span class="function">User <span class="title">findByName</span><span class="params">(<span class="meta">@Param(&quot;name&quot;)</span> String name)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Insert(&quot;INSERT INTO user(name, age) VALUES(#&#123;name&#125;, #&#123;age&#125;)&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">insert</span><span class="params">(<span class="meta">@Param(&quot;name&quot;)</span> String name, <span class="meta">@Param(&quot;age&quot;)</span> Integer age)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Update(&quot;UPDATE user SET age=#&#123;age&#125; WHERE name=#&#123;name&#125;&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">update</span><span class="params">(User user)</span></span>;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Delete(&quot;DELETE FROM user WHERE id =#&#123;id&#125;&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">delete</span><span class="params">(Long id)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="返回结果绑定"><a href="#返回结果绑定" class="headerlink" title="返回结果绑定"></a>返回结果绑定</h5><p>对于增、删、改操作相对变化较小。而对于“查”操作，我们往往需要进行多表关联，汇总计算等操作，那么对于查询的结果往往就不再是简单的实体对象了，往往需要返回一个与数据库实体不同的包装类，那么对于这类情况，就可以通过<code>@Results</code>和<code>@Result</code>注解来进行绑定，具体如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Results(&#123;</span></span><br><span class="line"><span class="meta">    @Result(property = &quot;name&quot;, column = &quot;name&quot;),</span></span><br><span class="line"><span class="meta">    @Result(property = &quot;age&quot;, column = &quot;age&quot;)</span></span><br><span class="line"><span class="meta">&#125;)</span></span><br><span class="line"><span class="meta">@Select(&quot;SELECT name, age FROM user&quot;)</span></span><br><span class="line"><span class="function">List&lt;User&gt; <span class="title">findAll</span><span class="params">()</span></span>;</span><br></pre></td></tr></table></figure>

<p>在上面代码中，@Result中的property属性对应User对象中的成员名，column对应SELECT出的字段名。</p>
<h4 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h4><p>真正在开发业务逻辑时，我们通常在service层接口中使用<code>@Transactional</code>来对各个业务逻辑进行事务管理的配置，例如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserService</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Transactional</span></span><br><span class="line">    <span class="function">User <span class="title">update</span><span class="params">(String name, String password)</span></span>;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="缓存"><a href="#缓存" class="headerlink" title="缓存"></a>缓存</h3><p>随着时间的积累，应用的使用用户不断增加，数据规模也越来越大，往往数据库查询操作会成为影响用户使用体验的瓶颈，此时使用缓存往往是解决这一问题非常好的手段之一。Spring 3开始提供了强大的基于注解的缓存支持，可以通过注解配置方式低侵入的给原有Spring应用增加缓存功能，提高数据访问性能</p>
<p>第一步：在<code>pom.xml</code>中引入cache依赖，添加如下内容：</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>

<p>第二步：在Spring Boot主类中增加<code>@EnableCaching</code>注解开启缓存功能，如下：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@EnableCaching</span></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chapter51Application</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		SpringApplication.run(Chapter51Application.class, args);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第三步：在数据访问接口中，增加缓存配置注解，如：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@CacheConfig(cacheNames = &quot;users&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">UserRepository</span> <span class="keyword">extends</span> <span class="title">JpaRepository</span>&lt;<span class="title">User</span>, <span class="title">Long</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Cacheable</span></span><br><span class="line">    <span class="function">User <span class="title">findByName</span><span class="params">(String name)</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>第四步：再来执行以下单元测试，可以在控制台中输出了下面的内容</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">Hibernate: insert into user (age, name, id) values (?, ?, ?)</span><br><span class="line">Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?</span><br><span class="line">第一次查询：10</span><br><span class="line">第二次查询：10</span><br></pre></td></tr></table></figure>

<p>到这里，我们可以看到，在调用第二次<code>findByName</code>函数时，没有再执行select语句，也就直接减少了一次数据库的读取操作。</p>
<h4 id="Cache配置注解详解"><a href="#Cache配置注解详解" class="headerlink" title="Cache配置注解详解"></a>Cache配置注解详解</h4><p>回过头来我们再来看这里使用到的两个注解分别作了什么事情：</p>
<ul>
<li><p><code>@CacheConfig</code>：主要用于配置该类中会用到的一些共用的缓存配置。在这里<code>@CacheConfig(cacheNames = &quot;users&quot;)</code>：配置了该数据访问对象中返回的内容将存储于名为users的缓存对象中，我们也可以不使用该注解，直接通过<code>@Cacheable</code>自己配置缓存集的名字来定义。</p>
</li>
<li><p>```<br>@Cacheable</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line">  ：配置了findByName函数的返回值将被加入缓存。同时在查询时，会先从缓存中获取，若不存在才再发起对数据库的访问。该注解主要有下面几个参数：</span><br><span class="line"></span><br><span class="line">  - `value`、`cacheNames`：两个等同的参数（`cacheNames`为Spring 4新增，作为`value`的别名），用于指定缓存存储的集合名。由于Spring 4中新增了`@CacheConfig`，因此在Spring 3中原本必须有的`value`属性，也成为非必需项了</span><br><span class="line">  - `key`：缓存对象存储在Map集合中的key值，非必需，缺省按照函数的所有参数组合作为key值，若自己配置需使用SpEL表达式，比如：`@Cacheable(key = &quot;#p0&quot;)`：使用函数第一个参数作为缓存的key值，更多关于SpEL表达式的详细内容可参考[官方文档](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html#cache-spel-context)</span><br><span class="line">  - `condition`：缓存对象的条件，非必需，也需使用SpEL表达式，只有满足表达式条件的内容才会被缓存，比如：`@Cacheable(key = &quot;#p0&quot;, condition = &quot;#p0.length() &lt; 3&quot;)`，表示只有当第一个参数的长度小于3的时候才会被缓存，若做此配置上面的AAA用户就不会被缓存，读者可自行实验尝试。</span><br><span class="line">  - `unless`：另外一个缓存条件参数，非必需，需使用SpEL表达式。它不同于`condition`参数的地方在于它的判断时机，该条件是在函数被调用之后才做判断的，所以它可以通过对result进行判断。</span><br><span class="line">  - `keyGenerator`：用于指定key生成器，非必需。若需要指定一个自定义的key生成器，我们需要去实现`org.springframework.cache.interceptor.KeyGenerator`接口，并使用该参数来指定。需要注意的是：**该参数与`key`是互斥的**</span><br><span class="line">  - `cacheManager`：用于指定使用哪个缓存管理器，非必需。只有当有多个时才需要使用</span><br><span class="line">  - `cacheResolver`：用于指定使用那个缓存解析器，非必需。需通过`org.springframework.cache.interceptor.CacheResolver`接口来实现自己的缓存解析器，并用该参数指定。</span><br><span class="line"></span><br><span class="line">除了这里用到的两个注解之外，还有下面几个核心注解：</span><br><span class="line"></span><br><span class="line">- `@CachePut`：配置于函数上，能够根据参数定义条件来进行缓存，它与`@Cacheable`不同的是，它每次都会真是调用函数，所以主要用于数据新增和修改操作上。它的参数与`@Cacheable`类似，具体功能可参考上面对`@Cacheable`参数的解析</span><br><span class="line"></span><br><span class="line">- ```</span><br><span class="line">  @CacheEvict</span><br></pre></td></tr></table></figure>

<p>：配置于函数上，通常用在删除方法上，用来从缓存中移除相应数据。除了同</p>
<figure class="highlight plaintext"><table><tr><td class="code"><pre><span class="line">@Cacheable</span><br></pre></td></tr></table></figure>

<p>一样的参数之外，它还有下面两个参数：</p>
<ul>
<li><code>allEntries</code>：非必需，默认为false。当为true时，会移除所有数据</li>
<li><code>beforeInvocation</code>：非必需，默认为false，会在调用方法之后移除数据。当为true时，会在调用方法之前移除数据。</li>
</ul>
</li>
</ul>
<h3 id="async实现异步任务"><a href="#async实现异步任务" class="headerlink" title="async实现异步任务"></a>async实现异步任务</h3><p>若这三个任务本身之间不存在依赖关系，可以并发执行的话，同步调用在执行效率方面就比较差，可以考虑通过异步调用的方式来并发执行。</p>
<p>在Spring Boot中，我们只需要通过使用<code>@Async</code>注解就能简单的将原来的同步函数变为异步函数，Task类改在为如下模式：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Slf4j</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">AsyncTasks</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Random random = <span class="keyword">new</span> Random();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Async</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTaskOne</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;开始做任务一&quot;</span>);</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        Thread.sleep(random.nextInt(<span class="number">10000</span>));</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        log.info(<span class="string">&quot;完成任务一，耗时：&quot;</span> + (end - start) + <span class="string">&quot;毫秒&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Async</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTaskTwo</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;开始做任务二&quot;</span>);</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        Thread.sleep(random.nextInt(<span class="number">10000</span>));</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        log.info(<span class="string">&quot;完成任务二，耗时：&quot;</span> + (end - start) + <span class="string">&quot;毫秒&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Async</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">doTaskThree</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        log.info(<span class="string">&quot;开始做任务三&quot;</span>);</span><br><span class="line">        <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">        Thread.sleep(random.nextInt(<span class="number">10000</span>));</span><br><span class="line">        <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">        log.info(<span class="string">&quot;完成任务三，耗时：&quot;</span> + (end - start) + <span class="string">&quot;毫秒&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为了让@Async注解能够生效，还需要在Spring Boot的主程序中配置@EnableAsync，如下所示：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@EnableAsync</span></span><br><span class="line"><span class="meta">@SpringBootApplication</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Chapter75Application</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        SpringApplication.run(Chapter75Application.class, args);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此时可以反复执行单元测试，您可能会遇到各种不同的结果，比如：</p>
<ul>
<li>没有任何任务相关的输出</li>
<li>有部分任务相关的输出</li>
<li>乱序的任务相关的输出</li>
<li>原因是目前<code>doTaskOne</code>、<code>doTaskTwo</code>、<code>doTaskThree</code>三个函数的时候已经是异步执行了。主程序在异步调用之后，主程序并不会理会这三个函数是否执行完成了，由于没有其他需要执行的内容，所以程序就自动结束了，导致了不完整或是没有输出任务相关内容的情况。</li>
</ul>
<h4 id="异步回调"><a href="#异步回调" class="headerlink" title="异步回调"></a>异步回调</h4><p>为了让<code>doTaskOne</code>、<code>doTaskTwo</code>、<code>doTaskThree</code>能正常结束，假设我们需要统计一下三个任务并发执行共耗时多少，这就需要等到上述三个函数都完成调动之后记录时间，并计算结果。</p>
<p>那么我们如何判断上述三个异步调用是否已经执行完成呢？我们需要使用<code>CompletableFuture&lt;T&gt;</code>来返回异步调用的结果，就像如下方式改造<code>doTaskOne</code>函数：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">    <span class="meta">@Async</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> CompletableFuture&lt;String&gt; <span class="title">doTaskOne</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    log.info(<span class="string">&quot;开始做任务一&quot;</span>);</span><br><span class="line">    <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line">    Thread.sleep(random.nextInt(<span class="number">10000</span>));</span><br><span class="line">    <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">    log.info(<span class="string">&quot;完成任务一，耗时：&quot;</span> + (end - start) + <span class="string">&quot;毫秒&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> CompletableFuture.completedFuture(<span class="string">&quot;任务一完成&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>按照如上方式改造一下其他两个异步函数之后，下面我们改造一下测试用例，让测试在等待完成三个异步调用之后来做一些其他事情。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">    CompletableFuture&lt;String&gt; task1 = asyncTasks.doTaskOne();</span><br><span class="line">    CompletableFuture&lt;String&gt; task2 = asyncTasks.doTaskTwo();</span><br><span class="line">    CompletableFuture&lt;String&gt; task3 = asyncTasks.doTaskThree();</span><br><span class="line"></span><br><span class="line">    CompletableFuture.allOf(task1, task2, task3).join();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">    log.info(<span class="string">&quot;任务全部完成，总耗时：&quot;</span> + (end - start) + <span class="string">&quot;毫秒&quot;</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2021/11/19/springboot简单学习/">https://chengsong.info/2021/11/19/springboot简单学习/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/springboot/">springboot</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2021/11/19/mini-vue3%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/"><i class="fa fa-chevron-left">  </i><span>mini-vue3</span></a></div><div class="next-post pull-right"><a href="/2021/06/05/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%A4%8D%E4%B9%A0/"><span>嵌入式复习</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>